<template>
  <div class="home-continer">
    <!-- 头部区域 -->
    <van-nav-bar title="标题" fixed>
      <!-- 右侧插槽 -->
      <template #right>
        <van-icon name="search" size="18" @click="$router.push('/search')" />
      </template>
      <template #left>
        <img src="../../assets/toutiao_logo.png" alt="" class="logo" />
      </template>
    </van-nav-bar>
    <!-- 频道列表区 -->
    <!-- beforeChange的回调会在将要切换标签页的时候会触发 -->
    <van-tabs
      v-model="active"
      sticky
      :before-change="beforeChange"
      @change="onTabsChange"
    >
      <van-tab :title="item.name" v-for="item in channels" :key="item.id">
        <Artlist :channel-id="item.id"></Artlist>
      </van-tab>
    </van-tabs>
    <van-popup v-model="show" :close-on-click-overlay="false">
      <div class="popup-container">
        <!-- 弹出层的头部区域 -->
        <van-nav-bar title="频道管理">
          <template #right>
            <van-icon
              name="cross"
              size="14"
              color="white"
              @click="show = false"
            />
          </template>
        </van-nav-bar>

        <!-- 弹出层的主体区域 -->
        <div class="pop-body">
          <!-- 我的频道 -->
          <div class="my-channel-box">
            <div class="channel-title">
              <div>
                <span class="title-bold">已添加频道：</span>
                <span class="title-gray">{{
                  isDel ? "点击移除频道" : "点击进入频道"
                }}</span>
              </div>
              <span class="btn-edit" @click="isDel = !isDel">{{
                isDel ? "完成" : "编辑"
              }}</span>
            </div>
            <!-- 我的频道列表 -->
            <van-row type="flex">
              <van-col span="6" v-for="(item, i) in channels" :key="item.id">
                <!-- 用户的频道 Item 项 -->
                <div
                  class="channel-item van-hairline--surround"
                  @click="onUserChannelClick(item, i)"
                >
                  {{ item.name }}
                  <!-- 删除的图标 x-->
                  <van-badge
                    color="transparent"
                    class="cross-badge"
                    v-if="isDel && item.name !== '推荐' && channels.length > 2"
                  >
                    <template #content>
                      <van-icon
                        name="cross"
                        class="badge-icon"
                        color="#cfcfcf"
                        size="12"
                      />
                    </template>
                  </van-badge>
                </div>
              </van-col>
            </van-row>
          </div>

          <!-- 分隔线 -->
          <div class="van-hairline--top sp-line"></div>

          <!-- 更多频道 -->
          <div class="more-channel-box">
            <div class="channel-title">
              <div>
                <span class="title-bold">可添加频道：</span>
                <span class="title-gray">点击添加频道</span>
              </div>
            </div>
            <!-- 更多频道列表 -->
            <van-row type="flex">
              <van-col span="6" v-for="item in moreChannel" :key="item.id">
                <div
                  class="channel-item van-hairline--surround"
                  @click="addToChannel(item)"
                >
                  {{ item.name }}
                </div>
              </van-col>
            </van-row>
          </div>
        </div>
      </div>
    </van-popup>
    <van-icon name="plus" size="16" class="plus" @click="show = true" />
  </div>
</template>

<script>
import { getUserChannelsApi, getAllChannelAPI, updateUserChannelAPI } from '../../api/homeApi'
import Artlist from '../../components/Artlist/Artlist.vue'
import { Notify } from 'vant'
import mix from '../../maxins/scroll.js'
// 第一一个对象,存储'频道名称'和'滚动位置'的对应关系
const nameMapTop = {

}
export default {
  // 通过mixins数组,把导入过来的模块成员混入到当前组件中
  mixins: [mix],
  data () {
    return {
      active: 0,
      channels: [],
      show: false,
      allChannel: [],
      // 是否处于删除状态,默认不处于删除状态
      isDel: false
    }
  },
  computed: {
    moreChannel () {
      const newArr = []
      // 1.循环全部频道
      this.allChannel.forEach(item => {
        // 2.判断是否在channels中
        const r = this.channels.every(x => x.id !== item.id)
        // 3.如果不在则添加在新数组中
        if (r) {
          newArr.push(item)
        }
      })
      return newArr
    }
  },
  created () {
    this.initUserChannels()
    this.initAllChannelAPI()
  },

  methods: {

    async initUserChannels () {
      const { data: res } = await getUserChannelsApi()
      console.log(res.data)
      this.channels = res.data.channels
    },
    async initAllChannelAPI () {
      const { data: res } = await getAllChannelAPI()
      if (res.message === 'OK') {
        this.allChannel = res.data.channels
        console.log(res)
      }
    },
    // 点击未关注的频道,将他添加到已关注的列表中
    addToChannel (item) {
      this.channels.push(item)
      // 准备参数
      this.saveUserChannel()
    },
    // 点击用户频道的item
    onUserChannelClick (item, i) {
      if (this.isDel) {
        if (item.name === '推荐' || this.channels.length === 2) { return }
        this.channels = this.channels.filter(x => x.id !== item.id)
        // 优化,因为有计算属性所以可以直接删除
        // this.channels.splice(item, 1)
        this.saveUserChannel()
      } else {
        this.active = i
        this.show = false
      }
    },
    // 封装的请求接口
    async saveUserChannel () {
      const newArr = this.channels.map((item, i) => {
        return { id: item.id, seq: i }
      })
      // 调用接口
      const { data: res } = await updateUserChannelAPI(newArr)
      if (res.message === 'OK') {
        // 成功通知
        Notify({ type: 'success', message: '添加成功' })
      }
      console.log(res)
    },
    // 将要实现标签页切换的时候会触发
    beforeChange () {
      console.log(window.scrollY)
      // 获取当前激活的频道的名称
      const name = this.channels[this.active].name
      // 获取当前频道滚动的位置
      const top = window.scrollY
      nameMapTop[name] = top
      console.log(nameMapTop)
      // 表示允许标签页的切换
      return true
    },
    // 标签页
    async onTabsChange () {
      const name = this.channels[this.active].name
      const top = nameMapTop[name] || 0
      await this.$nextTick()
      window.scrollTo(0, top)
      console.log(this.active)
    }

  },
  /*  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
  beforeRouteLeave (to, from, next) {
    // from.meta.top = window.scrollY
    // 在通过路由导航的方式,离开Home.vue组建的时候
    // 把滚动条的位置,记录到当前路由规则的meta元信息
    this.$route.meta.top = window.scrollY

    next()
  }, */

  components: {
    Artlist
  }
}
</script>

<style lang="less" scoped>
.logo {
  height: 80%;
}
.home-continer {
  padding-top: 46px;
  padding-bottom: 50px;
}
.plus {
  position: fixed;
  top: 58px;
  right: 10px;
  z-index: 999;
}
/deep/ .van-tabs__wrap {
  padding-right: 36px;
  background-color: white;
}
.van-popup,
.popup-container {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
    .title-bold {
      font-weight: bold;
    }
    .title-gray {
      color: gray;
      font-size: 12px;
    }
  }
}

.btn-edit {
  border: 1px solid #a3a2a2;
  padding: 0 10px;
  line-height: 20px;
  height: 20px;
  border-radius: 6px;
  font-size: 12px;
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 6px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}

.sp-line {
  margin: 10px 0 20px 0;
}
</style>
